import React from 'react';
import {
  Form,
  Checkbox,
  Descriptions,
  Input,
  Button,
  Carousel,
  message,
} from 'antd';
import { keys, findIndex } from 'lodash/fp';
import { executionProcess } from 'services/process';
import 'assets/css/carousel.css';
import { editXML } from 'utils/editXML';
import { PrevArrow, NextArrow } from 'components/CarouselArrows';

class BpmnForm extends React.Component {
  handleSubmit = async () => {
    const { form, xml, name } = this.props;
    try {
      await form.validateFields();
      const newXML = editXML(xml, form.getFieldsValue());
      const formData = new FormData();
      formData.append('name', name);
      const file = new File([newXML], name, {
        type: 'text/plain',
      });
      formData.append('file', file);
      // console.log(newXML);
      await executionProcess(formData);
      message.success('成功开始运行');
    } catch (error) {
      message.error('请检查所有任务是否已选择对应服务实例且参数已配置!');
      console.error(error);
    }
  };

  render() {
    const { form, dataSource, taskId } = this.props;
    const { getFieldDecorator, getFieldValue } = form;
    const descriptionList = dataSource.map((i) => (
      <Descriptions bordered key={i.taskId} column={3}>
        <Descriptions.Item label="活动 id" span={3}>
          {i.taskId}
        </Descriptions.Item>
        <Descriptions.Item label="服务名称">{i.serviceName}</Descriptions.Item>
        <Descriptions.Item label="接口名称" span={2}>
          {i.interfaceName}
        </Descriptions.Item>
        <Descriptions.Item label="接口参数" span={3}>
          {keys(i.params).map((j) => (
            <Form.Item label={j} style={{ margin: '5px' }} key={j}>
              {getFieldDecorator(`${i.taskId}.params[${j}]`, {
                initialValue: i.params[j],
                rules: [{ required: true, message: '请输入参数！' }],
              })(<Input />)}
            </Form.Item>
          ))}
          {keys(i.input).map((j) => (
            <Form.Item label={j} style={{ margin: '5px' }} key={j}>
              <span>
                {`使用来自 ${i.input[j].split('.')[0]} 的输出 ${
                  i.input[j].split('.')[1]
                } (不可修改)`}

              </span>
            </Form.Item>
          ))}
        </Descriptions.Item>
        <Descriptions.Item label="服务实例">
          <Form.Item style={{ margin: 0 }}>
            {getFieldDecorator(`${i.taskId}.instances`, {
              rules: [
                {
                  validator: (rule, value, callback) => {
                    const temp = getFieldValue(`${i.taskId}.instances`);
                    if (temp && temp.length !== 0) callback();
                    else {
                      callback('请选择服务实例！');
                    }
                  },
                },
              ],
            })(<Checkbox.Group options={keys(i.instances)} />)}
          </Form.Item>
        </Descriptions.Item>
      </Descriptions>
    ));
    if (taskId && taskId !== '') {
      const showId = findIndex((item) => item.taskId === taskId)(dataSource);
      // TODO: fix bug when checkbox clicked causes rerendering and this goto unexpected slide
      // probably we should wait for antd v4 to get rid of `getFieldDecorator` which
      // triggers rerendering of the whole component.
      // related issues:
      // - https://github.com/ant-design/ant-design/issues/13063
      // - https://github.com/ant-design/ant-design/issues/16911
      this.slider.slick.slickGoTo(showId);
    }
    return (
      <>
        <Carousel
          dots
          adaptiveHeight
          arrows
          style={{ margin: '20px' }}
          prevArrow={<PrevArrow />}
          nextArrow={<NextArrow />}
          ref={(slider) => {
            this.slider = slider;
          }}
        >
          {descriptionList}
        </Carousel>
        <Button
          onClick={this.handleSubmit}
          style={{ marginLeft: '20px' }}
          type="primary"
        >
          运行
        </Button>
      </>
    );
  }
}

export default Form.create({})(BpmnForm);
